import { initializeApp } from 'firebase/app'
import { GoogleAuthProvider, getAuth, signInWithPopup, signOut } from 'firebase/auth'

const firebaseConfig = {
  apiKey: 'AIzaSyBy5IWupQufH8vK6dX8yOZgw1OtFVYcEdo',
  authDomain: 'redgrowth.firebaseapp.com',
  projectId: 'redgrowth',
  storageBucket: 'redgrowth.appspot.com',
  messagingSenderId: '962934206664',
  appId: '1:962934206664:web:dd8c4ecd71fac1451235fd',
  measurementId: 'G-H61YXNF6EP',
}
const app = initializeApp(firebaseConfig)
const auth = getAuth(app)
const provider = new GoogleAuthProvider()

export const _signUpWithGoogle = () => {
  return new Promise((resolve, reject) => {
    signInWithPopup(auth, provider)
      .then(result => {
        const { email, displayName, photoURL } = result.user
        const postData = {
          email,
          nickname: displayName,
          avatar: photoURL,
          type: 'google',
          source: 3,
        }
        resolve(postData)
      })
      .catch(error => {
        // Handle Errors here.
        const errorCode = error.code
        const errorMessage = error.message
        // The email of the user's account used.
        const email = error.customData.email
        // The AuthCredential type that was used.
        const credential = GoogleAuthProvider.credentialFromError(error)
        // ...
      })
  })
}

export const _signOut = () => {
  signOut(auth)
    .then(() => {
      // Sign-out successful.
    })
    .catch(error => {
      // An error happened.
    })
}
